<template>
  <view class="purchase-request-edit-container">
    <view class="page-header">
      <text class="page-title">编辑采购申请</text>
      <text class="page-subtitle">修改采购申请信息</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section">
        <text class="section-title">申请信息</text>
        
        <view class="form-item">
          <text class="form-label required">申请人ID</text>
          <uni-easyinput 
            v-model="formData.applicant_id"
            placeholder="请输入申请人ID"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.applicant_id" class="error-text">{{ errors.applicant_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">申请人类型</text>
          <radio-group @change="onApplicantTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.applicant_type === 1" color="#007aff"/>
              <text class="radio-text">医生</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.applicant_type === 2" color="#007aff"/>
              <text class="radio-text">员工</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">采购内容</text>
        
        <view class="form-item">
          <text class="form-label required">采购类型</text>
          <radio-group @change="onPurchaseTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.purchase_type === 1" color="#007aff"/>
              <text class="radio-text">商品</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.purchase_type === 2" color="#007aff"/>
              <text class="radio-text">物资</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label required">选择{{ purchaseTypeText }}</text>
          <button class="select-btn" @click="showItemPicker">
            <text class="select-btn-text">{{ selectedItemName || '点击选择' + purchaseTypeText }}</text>
            <text class="select-btn-icon">›</text>
          </button>
          <text v-if="errors.item_id" class="error-text">{{ errors.item_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">申请数量</text>
          <uni-easyinput 
            v-model="formData.quantity"
            type="number"
            placeholder="请输入申请数量"
            :clearable="true"
          />
          <text v-if="errors.quantity" class="error-text">{{ errors.quantity }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">申请原因</text>
          <textarea 
            v-model="formData.reason" 
            class="form-textarea" 
            placeholder="请输入申请原因"
            maxlength="500"
          />
          <text v-if="errors.reason" class="error-text">{{ errors.reason }}</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">优先级</text>
        
        <view class="form-item">
          <text class="form-label required">紧急程度</text>
          <radio-group @change="onUrgencyChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.urgency_level === 1" color="#007aff"/>
              <text class="radio-text">普通</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.urgency_level === 2" color="#007aff"/>
              <text class="radio-text">紧急</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.urgency_level === 3" color="#007aff"/>
              <text class="radio-text">特急</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>

    <!-- 选择器弹窗 -->
    <view v-if="showPicker" class="picker-modal" @click="closePicker">
      <view class="picker-content" @click.stop>
        <view class="picker-header">
          <text class="picker-title">选择{{ purchaseTypeText }}</text>
          <button class="close-btn" @click="closePicker">×</button>
        </view>
        
        <view class="picker-search">
          <uni-easyinput 
            v-model="searchKeyword"
            placeholder="搜索名称或编码"
            :clearable="true"
            @input="filterItems"
          />
        </view>
        
        <scroll-view class="picker-list" scroll-y>
          <view v-if="filteredItems.length === 0" class="empty-tip">暂无数据</view>
          <view v-for="item in filteredItems" :key="item._id" class="picker-item" @click="selectItem(item)">
            <view class="picker-item-info">
              <text class="picker-item-name">{{ item.name }}</text>
              <text class="picker-item-code">{{ item.code }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const pageLoading = ref(true)
const requestId = ref('')

const formData = reactive({
  applicant_id: '',
  applicant_type: 1,
  purchase_type: 1,
  item_id: '',
  item_code: '',
  item_name: '',
  quantity: '',
  reason: '',
  urgency_level: 1,
  approval_status: 0
})

const errors = reactive({
  applicant_id: '',
  item_id: '',
  quantity: '',
  reason: ''
})

const showPicker = ref(false)
const searchKeyword = ref('')
const allItems = ref([])
const filteredItems = ref([])
const selectedItemName = ref('')

const purchaseTypeText = computed(() => {
  return formData.purchase_type === 1 ? '商品' : '物资'
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  requestId.value = currentPage.options.id || ''
  
  if (!requestId.value) {
    uni.showToast({ title: '缺少申请ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/purchase_requests/list' })
    }, 1500)
    return
  }
  
  await loadRequestData()
  pageLoading.value = false
})

async function loadRequestData() {
  try {
    // 调用云对象方法获取采购申请信息
    const purchaseRequestsObj = uniCloud.importObject('dh-purchase_requests')
    const result = await purchaseRequestsObj.getPurchaseRequestById(requestId.value)
    
    if (result.code === 200 && result.data) {
      const data = result.data
      Object.assign(formData, {
        applicant_id: data.applicant_id || '',
        applicant_type: data.applicant_type || 1,
        purchase_type: data.purchase_type || 1,
        item_id: data.item_id || '',
        item_code: data.item_code || '',
        item_name: data.item_name || '',
        quantity: data.quantity?.toString() || '',
        reason: data.reason || '',
        urgency_level: data.urgency_level || 1,
        approval_status: data.approval_status || 0
      })
      
      if (data.item_name) {
        selectedItemName.value = data.item_name
      }
    } else {
      throw new Error(result.message || '采购申请不存在')
    }
  } catch (err) {
    console.error('加载申请数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/purchase_requests/list' })
    }, 1500)
  }
}

function onApplicantTypeChange(e) {
  formData.applicant_type = parseInt(e.detail.value)
}

function onPurchaseTypeChange(e) {
  formData.purchase_type = parseInt(e.detail.value)
  formData.item_id = ''
  formData.item_code = ''
  formData.item_name = ''
  selectedItemName.value = ''
  errors.item_id = ''
}

function onUrgencyChange(e) {
  formData.urgency_level = parseInt(e.detail.value)
}

async function showItemPicker() {
  try {
    uni.showLoading({ title: '加载中...' })
    const db = uniCloud.database()
    
    let collection = formData.purchase_type === 1 ? 'dh-products' : 'dh-inventory'
    let res = await db.collection(collection)
      .field({
        _id: true,
        product_name: true,
        product_code: true,
        item_name: true,
        item_code: true
      })
      .limit(500)
      .get()
    
    const data = res.result?.data || res.data || []
    allItems.value = data.map(item => ({
      _id: item._id,
      name: item.product_name || item.item_name || '未命名',
      code: item.product_code || item.item_code || ''
    }))
    
    filteredItems.value = allItems.value
    showPicker.value = true
    uni.hideLoading()
  } catch (err) {
    console.error('加载数据失败:', err)
    uni.hideLoading()
    uni.showToast({ title: '加载失败', icon: 'none' })
  }
}

function filterItems() {
  const keyword = searchKeyword.value.toLowerCase().trim()
  if (!keyword) {
    filteredItems.value = allItems.value
  } else {
    filteredItems.value = allItems.value.filter(item => 
      item.name.toLowerCase().includes(keyword) || item.code.toLowerCase().includes(keyword)
    )
  }
}

function selectItem(item) {
  formData.item_id = item._id
  formData.item_code = item.code
  formData.item_name = item.name
  selectedItemName.value = item.name
  errors.item_id = ''
  closePicker()
}

function closePicker() {
  showPicker.value = false
  searchKeyword.value = ''
}

function validateForm() {
  let isValid = true
  
  if (!formData.applicant_id || formData.applicant_id.trim().length === 0) {
    errors.applicant_id = '请输入申请人ID'
    isValid = false
  } else {
    errors.applicant_id = ''
  }
  
  if (!formData.item_id) {
    errors.item_id = '请选择采购物品'
    isValid = false
  } else {
    errors.item_id = ''
  }
  
  if (!formData.quantity || parseInt(formData.quantity) <= 0) {
    errors.quantity = '请输入有效的申请数量'
    isValid = false
  } else {
    errors.quantity = ''
  }
  
  if (!formData.reason || formData.reason.trim().length === 0) {
    errors.reason = '请输入申请原因'
    isValid = false
  } else {
    errors.reason = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    const db = uniCloud.database()
    const submitData = {
      ...formData,
      quantity: parseInt(formData.quantity),
      update_time: Date.now()
    }
    
    // 调用云对象方法更新采购申请
    const purchaseRequestsObj = uniCloud.importObject('dh-purchase_requests')
    const result = await purchaseRequestsObj.updatePurchaseRequest(requestId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: result.message || '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/purchase_requests/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '更新失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/purchase_requests/list' })
}
</script>

<style lang="scss" scoped>
.purchase-request-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.select-btn {
  width: 100%;
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select-btn-text {
  font-size: 28rpx;
  color: #333;
}

.select-btn-icon {
  font-size: 40rpx;
  color: #999;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}

.picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.picker-content {
  width: 90%;
  max-height: 80vh;
  background: #fff;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
}

.picker-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  font-size: 48rpx;
  color: #999;
  background: none;
  border: none;
  padding: 0;
}

.picker-search {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.picker-list {
  flex: 1;
  overflow-y: auto;
}

.empty-tip {
  padding: 100rpx 0;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

.picker-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:active {
    background: #f5f5f5;
  }
}

.picker-item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.picker-item-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.picker-item-code {
  font-size: 24rpx;
  color: #999;
  margin-left: 20rpx;
}
</style>
